package com.aiyige.page.selectinterest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventInterestSelectedAllCleared;
import com.aiyige.base.eventbus.EventInterestSelectedStateChanged;
import com.aiyige.base.eventbus.EventPickRegion;
import com.aiyige.base.eventbus.EventSelectInterest;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.location.model.RegionData;
import com.aiyige.model.Channel;
import com.aiyige.model.tag.Tag;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.selectinterest.adapter.IndustryAdapter;
import com.aiyige.page.selectinterest.adapter.SelectInterestPagerAdapter;
import com.aiyige.page.selectinterest.model.IndustryItem;
import com.aiyige.page.selectinterest.model.InterestItem;
import com.aiyige.page.selectinterest.util.InterestUtil;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.AppUtils;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;
import timber.log.Timber;

@Route(path = ARouterConfig.SelectInterestPage)
public class SelectInterestPage extends AppCompatActivity {
    public static final int MAX_SELECT_NUM = 5;
    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.industryRv)
    RecyclerView industryRv;
    @BindView(R.id.selectInterestVp)
    ViewPager selectInterestVp;
    IndustryAdapter industryAdapter;
    List<IndustryItem> industryItemList = new LinkedList<>();
    @BindView(R.id.locationTv)
    TextView locationTv;
    RegionData regionData = null;
    BroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_select_interest);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        EventBus.getDefault().register(this);
        titleTv.setText(R.string.select);
        industryAdapter = new IndustryAdapter();
        industryRv.setLayoutManager(new LinearLayoutManager(this));
        industryRv.setAdapter(industryAdapter);
        industryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < industryAdapter.getItemCount(); ++i) {
                    industryAdapter.getItem(i).setSelected(i == position);
                }
                industryAdapter.notifyDataSetChanged();
                selectInterestVp.setCurrentItem(position, false);
            }
        });
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = "";
                try {
                    action = intent.getAction();
                } catch (Exception e) {

                }

                switch (action) {
                    case LocationService.ACTION_LOCATION_FINISH: {
                        LocationData locationData = null;
                        try {
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                        } catch (Exception e) {

                        }
                        if (locationData != null && locationData.isSuccess()) {
                            if (regionData == null) {
                                regionData = new RegionData(locationData.getCity(), locationData.getCountry() + " " + locationData.getProvince() + " " + locationData.getCity(), DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity()));
                                locationTv.setText(locationData.getProvince() + " " + locationData.getCity());
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
        };
        registerReceiver(receiver, new IntentFilter(LocationService.ACTION_LOCATION_FINISH));
        LocationService.startLocation(this);
        requestData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventInterestSelectedAllCleared(EventInterestSelectedAllCleared event) {
        industryAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventInterestSelectedStateChanged(EventInterestSelectedStateChanged event) {
        for (int i = 0; i < industryAdapter.getItemCount(); ++i) {
            if (industryAdapter.getItem(i).isStats()) {
                industryAdapter.notifyItemChanged(i + industryAdapter.getHeaderLayoutCount());
                break;
            }
        }

        for (int i = 0; i < industryAdapter.getItemCount(); ++i) {
            if (industryAdapter.getItem(i).getId().equals(event.getIndustryId())) {
                industryAdapter.notifyItemChanged(i + industryAdapter.getHeaderLayoutCount());
                break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void requestData() {
        new RequestDataTask().execute();
    }


    @OnClick({R.id.selectRegionLayout, R.id.confirmBtn, R.id.titleBackBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.selectRegionLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectRegionPage)
                        .withTransition(R.anim.activity_slide_in_bottom, R.anim.activity_still)
                        .navigation(this);
                break;
            case R.id.titleBackBtn:
                finish();
                overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                break;
            case R.id.confirmBtn:
                collectSelectInterest();
                doSelectRegion();
                EventBus.getDefault().post(new EventSelectInterest());
                EventBus.getDefault().post(new EventSelectRegion());
                overridePendingTransition(R.anim.activity_still, R.anim.activity_slide_out_bottom);
                finish();
                break;
            default:
                break;
        }
    }

    public void collectSelectInterest() {
        List<String> interestIdList = new LinkedList<>();
        List<String> interestNameList = new LinkedList<>();
        List<String> industryIdList = new LinkedList<>();
        List<String> industryNameList = new LinkedList<>();

        List<IndustryItem> selectedIndustryItemList = new LinkedList<>();
        outLoop:
        for (IndustryItem industryItem : industryItemList) {
            if (industryItem.isStats()) continue;
            List<InterestItem> interestItemList = industryItem.getInterestItemList();
            if (!industryItem.getSelectedInterestItemList().isEmpty()) {
                IndustryItem selectedIndustryItem = new IndustryItem();
                selectedIndustryItem.setId(industryItem.getId());
                selectedIndustryItem.setTitle(industryItem.getTitle());
                selectedIndustryItem.setInterestItemList(industryItem.getSelectedInterestItemList());
                selectedIndustryItemList.add(selectedIndustryItem);
                industryIdList.add(industryItem.getId());
                industryNameList.add(industryItem.getTitle());
            }
            for (InterestItem interestItem : interestItemList) {
                if (interestItem.isAllSelected()) {
                    if (interestItem.isSelected()) {
                        for (InterestItem i : interestItemList) {
                            if (i.isAllSelected()) {
                                continue;
                            }
                            interestIdList.add(i.getId());
                        }
                        interestNameList.add(industryItem.getTitle());
                        continue outLoop;
                    }
                } else {
                    if (interestItem.isSelected()) {
                        interestIdList.add(interestItem.getId());
                        interestNameList.add(interestItem.getTitle());
                    }
                }
            }
        }
        InterestUtil.setIndustryId(industryIdList);
        InterestUtil.setIndustryName(industryNameList);
        InterestUtil.setInterestSelectState(selectedIndustryItemList);
        InterestUtil.setInterestId(interestIdList);
        InterestUtil.setInterestName(interestNameList);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPickRegion(EventPickRegion event) {
        regionData = event.getRegionData();
        locationTv.setText(regionData.getCityName());
    }

    public void doSelectRegion() {
        LocationUtil.setCurrentUserSelectRegion(regionData);
    }

    public class RequestDataTask extends AsyncTask<Object, Object, Object> {
        LoadingDialog loadingDialog;
        List<IndustryItem> dataList = new LinkedList<>();

        @Override
        protected void onPreExecute() {
            loadingDialog = LoadingDialog.newBuilder()
                    .with(SelectInterestPage.this)
                    .show();
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().allChannel(BuildConfig.appVersion).execute();
                if (response.code() != ResponseCode.OK) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                } else {
                    List<Channel> channelList = new LinkedList<>();
                    String json = RetrofitUtil.getResponseBodyAsString(response);
                    channelList.addAll(JSON.parseArray(json, Channel.class));
                    for (Channel channel : channelList) {
                        IndustryItem industryItem = new IndustryItem();
                        industryItem.setTitle(channel.getName());
                        industryItem.setId(channel.getId());
                        dataList.add(industryItem);
                    }
                    populateSelectedItem();
                }
                return null;
            } catch (Exception e) {
                return e;
            }

        }

        @Override
        protected void onPostExecute(Object o) {
            loadingDialog.dismiss();
            if (o instanceof Exception) {
                ToastX.show(((Exception) o).getMessage());
            } else {
                restoreSelectState();
                industryItemList.clear();
                industryItemList.add(IndustryItem.STATE);
                industryItemList.addAll(dataList);
                industryAdapter.setNewData(industryItemList);
                selectInterestVp.setAdapter(new SelectInterestPagerAdapter(getSupportFragmentManager(), industryItemList));
            }
        }

        public void populateSelectedItem() {
            List<IndustryItem> selectedIndustryItemList = InterestUtil.getInterestSelectState();
            loopa:
            for (IndustryItem selectedIndustryItem : selectedIndustryItemList) {
                for (IndustryItem industryItem : dataList) {
                    if (selectedIndustryItem.getId().equals(industryItem.getId())) {
                        industryItem.getInterestItemList().add(InterestItem.newBuilder().allSelected(true).build());
                        try {
                            Response<ResponseBody> response = ApiManager.getService()
                                    .getSetup(SetupUtil.GROUP_TYPE_CATEGORY, BuildConfig.appVersion, industryItem.getId())
                                    .execute();
                            if (response.code() != ResponseCode.OK) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            } else {
                                String json = RetrofitUtil.getResponseBodyAsString(response);
                                List<Setup> setupList = JSON.parseArray(json, Setup.class);
                                for (Setup setup : setupList) {
                                    industryItem.getInterestItemList().add(InterestItem.newBuilder()
                                            .id(setup.getId())
                                            .title((String) setup.getData().get("name"))
                                            .build());
                                }
                            }
                            if (AccountUtil.isLogin()) {
                                response = ApiManager.getService()
                                        .getUserTag(AccountUtil.getCurrentUser().getId(), industryItem.getId(), SetupUtil.GROUP_TYPE_CATEGORY)
                                        .execute();
                                if (response.code() != ResponseCode.OK) {
                                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                } else {
                                    String json = RetrofitUtil.getResponseBodyAsString(response);
                                    List<Tag> tagList = JSON.parseArray(json, Tag.class);
                                    for (Tag tag : tagList) {
                                        industryItem.getInterestItemList().add(InterestItem.newBuilder()
                                                .id(tag.getId())
                                                .title(tag.getName())
                                                .build());
                                    }
                                }
                            }
                        } catch (Exception e) {
                            industryItem.getInterestItemList().clear();
                        }
                        continue loopa;
                    }
                }
            }
        }

        public void restoreSelectState() {
            List<IndustryItem> selectedIndustryItemList = InterestUtil.getInterestSelectState();
            loopa:
            for (IndustryItem selectedIndustryItem : selectedIndustryItemList) {
                List<InterestItem> selectedInterestItemList = selectedIndustryItem.getSelectedInterestItemList();
                for (IndustryItem industryItem : dataList) {
                    if (industryItem.isStats()) continue;
                    if (industryItem.getId().equals(selectedIndustryItem.getId())) {
                        List<InterestItem> interestItemList = industryItem.getInterestItemList();
                        loopb:
                        for (InterestItem selectedInterestItem : selectedInterestItemList) {
                            for (InterestItem interestItem : interestItemList) {
                                if (selectedInterestItem.getId().equals(interestItem.getId())) {
                                    interestItem.setSelected(true);
                                    continue loopb;
                                }
                            }
                        }
                        continue loopa;
                    }
                }
            }
        }
    }

}
